﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DiBang.Common;
using DiBang.Sql;
using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using Size = System.Drawing.Size;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
using System.Windows;
using System.IO;
using System.Drawing.Imaging;
using System.Configuration;


namespace ChangWuDiBang
{
    public partial class FrmDiBangImport : Office2007Form
    {
        private FilterInfoCollection videoDevices;
        //private VideoCaptureDevice videoSource;
        delegate void UpdateTextEventHandler(string text);  //委托，此为重点
        UpdateTextEventHandler updateText;

        public UserInfo _UserInfo
        {
            get;
            set;
        }

        SqlLib sqlLib = new SqlLib();
        SqlExtend sqlExtend = new SqlExtend();

        public FrmDiBangImport()
        {
            this.EnableGlass = false;
            InitializeComponent();
        }

        private void FrmDiBangImport_Load(object sender, EventArgs e)
        {
            try
            {
                this.txtUserID.ReadOnly = true;
                this.txtWeight.ReadOnly = true;
                splitContainer1.Panel1Collapsed = false;
                splitContainer1.Panel2Collapsed = true;

                splitContainer2.Panel1Collapsed = false;
                splitContainer2.Panel2Collapsed = true;


                this.txtUserID.Text = _UserInfo.UserID;
                //一直刷新时间
                lblVDate.Text = sqlExtend.GetSysTime();
                this.timer1.Enabled = true;
                this.timer1.Start();

                //初始化COM口
                SerialPortInit();

                // 枚举所有视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                foreach (FilterInfo device in videoDevices)
                {
                    cmbFirstCamera.Items.Add(device.Name);
                    cmbSecCamera.Items.Add(device.Name);
                }
                cmbFirstCamera.SelectedIndex = -1;
                cmbSecCamera.SelectedIndex = -1;
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        //接收SerialPort数据
        private void SerialPortInit()
        {
            string portName = ConfigurationManager.AppSettings["PortName"].ToString();
            string baudRate = ConfigurationManager.AppSettings["BaudRate"].ToString();
            int iBaudRate = int.Parse(baudRate);
            serialport = new System.IO.Ports.SerialPort(portName, iBaudRate);
            try
            {
                serialport.Close();
                serialport.Dispose();

                serialport.Open();
                lblVSerialPortState.Text = "端口OK!";
                lblVSerialPortState.BackColor = Color.LightGreen;
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                lblVSerialPortState.Text = "端口异常!";
                lblVSerialPortState.BackColor = Color.Red;
            }
        }

        private void serialport_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //byte[] readBuffer = new byte[serialport.ReadBufferSize];
            //spReceive.Read(readBuffer, 0, readBuffer.Length);
            //this.Invoke(updateText, new string[] { Encoding.Unicode.GetString(readBuffer) });

            string readString = serialport.ReadExisting();
            this.Invoke(updateText, new string[] { readString });
        }

        private void UpdateTextBox(string text)
        {
            txtWeight.Text = text;
        }

        private bool FirstCamera(string mode)
        {
            bool retBool = true;
            if (mode.ToUpper().Equals("CONNECT"))
            {
                VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[cmbFirstCamera.SelectedIndex].MonikerString);
                videoSource.DesiredFrameSize = new System.Drawing.Size(320, 240);
                videoSource.DesiredFrameRate = 1;

                vspFirst.VideoSource = videoSource;
                vspFirst.Start();
            }
            else if (mode.ToUpper().Equals("DISCONNECT"))
            {
                vspFirst.SignalToStop();
                vspFirst.WaitForStop();
            }
            else
            {
                MessageBoxEx.Show("输入模式不正确!", "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                retBool = false;    
            }

            return retBool;
        }

        private bool SecondCamera(string mode)
        {
            bool retBool = true;
            if (mode.ToUpper().Equals("CONNECT"))
            {
                VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[cmbSecCamera.SelectedIndex].MonikerString);
                videoSource.DesiredFrameSize = new System.Drawing.Size(320, 240);
                videoSource.DesiredFrameRate = 1;

                vspSec.VideoSource = videoSource;
                vspSec.Start();
            }
            else if (mode.ToUpper().Equals("DISCONNECT"))
            {
                vspSec.SignalToStop();
                vspSec.WaitForStop();
            }
            else
            {
                MessageBoxEx.Show("输入模式不正确!", "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                retBool = false;
            }

            return retBool;
        }

        private void btnFirstPhoto_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnFirstPhoto.Text == "拍照")
                {
                    if (vspFirst.IsRunning)
                    {
                        BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                        vspFirst.GetCurrentVideoFrame().GetHbitmap(),
                                        IntPtr.Zero,
                                         Int32Rect.Empty,
                                        BitmapSizeOptions.FromEmptyOptions());
                        PngBitmapEncoder pE = new PngBitmapEncoder();
                        pE.Frames.Add(BitmapFrame.Create(bitmapSource));

                        MemoryStream ms = new MemoryStream();
                        pE.Save(ms);

                        //Stream转换成图片
                        Image image = Image.FromStream(ms, true);
                        picFirst.Image = image;

                        //Byte[] imgbyte = new Byte[ms.Length];
                        //ms.Read(imgbyte, 0, imgbyte.Length);
                    }
                    
                    //转换视角
                    splitContainer1.Panel1Collapsed = true ;
                    splitContainer1.Panel2Collapsed = false;
                    btnFirstPhoto.Text = "返回";
                }
                else
                {
                    //转换视角
                    splitContainer1.Panel1Collapsed = false;
                    splitContainer1.Panel2Collapsed = true;
                    btnFirstPhoto.Text = "拍照";
                }
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnSecPhoto_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnSecPhoto.Text == "拍照")
                {
                    if (vspSec.IsRunning)
                    {
                        BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                        vspSec.GetCurrentVideoFrame().GetHbitmap(),
                                        IntPtr.Zero,
                                         Int32Rect.Empty,
                                        BitmapSizeOptions.FromEmptyOptions());
                        PngBitmapEncoder pE = new PngBitmapEncoder();
                        pE.Frames.Add(BitmapFrame.Create(bitmapSource));

                        MemoryStream ms = new MemoryStream();
                        pE.Save(ms);

                        //Stream转换成图片
                        Image image = Image.FromStream(ms, true);
                        picSec.Image = image;

                        //Byte[] imgbyte = new Byte[ms.Length];
                        //ms.Read(imgbyte, 0, imgbyte.Length);
                    }

                    //转换视角
                    splitContainer2.Panel1Collapsed = true;
                    splitContainer2.Panel2Collapsed = false;
                    btnSecPhoto.Text = "返回";
                }
                else
                {
                    //转换视角
                    splitContainer2.Panel1Collapsed = false;
                    splitContainer2.Panel2Collapsed = true;
                    btnSecPhoto.Text = "拍照";
                }
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnFirstConnet_Click(object sender, EventArgs e)
        {
            if (btnFirstConnet.Text == "断开")
            {
                if (FirstCamera("DISCONNET"))
                {
                    btnFirstConnet.Text = "连接";
                }
            }
            else
            {
                if (FirstCamera("CONNET"))
                {
                    btnFirstConnet.Text = "断开";
                }
            }
        }

        private void btnSecConnet_Click(object sender, EventArgs e)
        {
            if (btnSecConnet.Text == "断开")
            {
                if (SecondCamera("DISCONNET"))
                {
                    btnSecConnet.Text = "连接";
                }
            }
            else
            {
                if (SecondCamera("CONNET"))
                {
                    btnSecConnet.Text = "断开";
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!sqlExtend.UserPwdCheck(txtUserID.Text.Trim(), txtPwd.Text.Trim()))
                    throw new Exception("用户ID或密码不存在!");

                //检查栏位是否为空
                ParamCheck();

                DialogResult diaR = MessageBoxEx.Show("是否要保存?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (diaR == DialogResult.No)
                    return;

                MemoryStream msFirst = new MemoryStream();
                picFirst.Image.Save(msFirst, ImageFormat.Bmp);
                msFirst.Dispose();
                byte[] byteFirstPic = msFirst.GetBuffer();

                MemoryStream msSec = new MemoryStream();
                picSec.Image.Save(msSec, ImageFormat.Bmp);
                msSec.Dispose();
                byte[] byteSecPic = msSec.GetBuffer();

                string timeKey = sqlExtend.GetTimeKey();
                string imageID = "IMAGE_" + timeKey;

                //存入图片
                Dictionary<string, object> imageSet = new Dictionary<string, object>();
                imageSet.Clear();
                imageSet.Add("IMAGE_ID", imageID);
                imageSet.Add("FIRST_PHOTO", byteFirstPic);
                imageSet.Add("SECOND_PHOTO", byteSecPic);
                imageSet.Add("CREATE_USER_ID", txtUserID.Text.Trim());
                imageSet.Add("CREATE_TIME", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                imageSet.Add("LAST_EVENT_NAME", "IMAGE_CREATE");
                imageSet.Add("LAST_EVENT_USER_ID", txtUserID.Text.Trim());
                imageSet.Add("LAST_EVENT_TIMEKEY", timeKey);
                sqlLib.InsertTable("DB_IMAGE", imageSet);

                //存入记录的数据
                Dictionary<string, object> dibangSet = new Dictionary<string, object>();
                dibangSet.Clear();
                dibangSet.Add("CHENG_DATE", lblVDate.Text.Trim());
                dibangSet.Add("PIN_MING", txtPinMing.Text.Trim());
                dibangSet.Add("CHE_HAO", txtCheHao.Text.Trim());

                dibangSet.Add("WEIGHT", Base64Encoding.BaseEncoding(txtWeight.Text.Trim()));//进行编码加密

                dibangSet.Add("OTHER", txtOther.Text.Trim());
                dibangSet.Add("IMAGE_ID", imageID);
                dibangSet.Add("CREATE_USER_ID", txtUserID.Text.Trim());
                dibangSet.Add("CREATE_TIME", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                dibangSet.Add("LAST_EVENT_NAME", "Create");
                dibangSet.Add("LAST_EVENT_USER_ID", txtUserID.Text.Trim());
                dibangSet.Add("LAST_EVENT_TIMEKEY", timeKey);
                if (sqlLib.InsertTable("DB_DIBANG", dibangSet) >= -1)
                {
                    sqlExtend.MakeDiBangHistory(timeKey);//插入履历
                    MessageBoxEx.Show("输入存入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //Show出报表界面
                    DiBangPrintInfo dibangPrintInfo = new DiBangPrintInfo();
                    dibangPrintInfo.ChengZhongDate = lblVDate.Text.Trim();
                    dibangPrintInfo.PinMing = txtPinMing.Text.Trim();
                    dibangPrintInfo.CheHao = txtCheHao.Text.Trim();
                    dibangPrintInfo.ChengZhong = txtWeight.Text.Trim();
                    dibangPrintInfo.ChengZhongOther = txtOther.Text.Trim();
                    dibangPrintInfo.ChengZhongOwer = _UserInfo.UserName;
                    dibangPrintInfo.FromPicPath = Convert.ToBase64String(byteFirstPic);//报表文件显示
                    dibangPrintInfo.ToPicPath = Convert.ToBase64String(byteSecPic);//报表文件显示
                    dibangPrintInfo.PrintUserName = _UserInfo.UserName;

                    FrmDiBangPrint frmDiBangPrint = new FrmDiBangPrint();
                    frmDiBangPrint._DiBangPrintInfo = dibangPrintInfo;
                    frmDiBangPrint.ShowDialog();
                }
                else
                {
                    MessageBoxEx.Show("存入失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                txtPwd.Clear();
                txtComment.Clear();
                txtPinMing.Clear();
                txtCheHao.Clear();
                txtOther.Clear();

                //
                picFirst.Image = null;
                picSec.Image = null;
                btnFirstPhoto.Text = "拍照";
                btnSecPhoto.Text = "拍照";
            }
        }

        /// <summary>
        /// 品名/车号/第一摄像头照片/第二摄像头照片不能为空
        /// </summary>
        private void ParamCheck()
        {
            if (string.IsNullOrEmpty(txtPinMing.Text.Trim()))
            {
                txtPinMing.Focus();
                throw new Exception("品名不能为空!");
            }
            if (string.IsNullOrEmpty(txtCheHao.Text.Trim()))
            {
                txtCheHao.Focus();
                throw new Exception("车号不能为空!");
            }

            if (picFirst.Image == null)
            {
                throw new Exception("第一摄像头的图片为空!");
            }

            if (picSec.Image == null)
            {
                throw new Exception("第二摄像头的图片为空!");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            lblVDate.Text = sqlExtend.GetSysTime();
        }

        private void FrmDiBangImport_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.serialport.Dispose();
            this.serialport.Close();
        }
    }
}
